#include "data_global.h"
#include "link_list.h"

extern linklist linkHead;

extern pthread_mutex_t mutex_linklist;
extern pthread_mutex_t mutex_analysis;

extern pthread_cond_t cond_analysis;
extern pthread_cond_t cond_refresh;


struct env_info *shm_buf;

#define N 1024

void init_mem()
{
    key_t key_info;
    int shmid, semid;

    if ((key_info = ftok ("/app", 'i')) < 0)
    {
        perror ("ftok info");
        exit (-1);
    }
    
    if ((shmid = shmget (key_info, N, IPC_CREAT | IPC_EXCL | 0666)) < 0)
    {
        if (errno == EEXIST)
        {
            shmid = shmget (key_info, N, 0666);
            shm_buf = (struct env_info *)shmat (shmid, NULL, 0);

        }
        else
        {
            perror ("shmget");
            exit (-1);
        }

    }
    else
    {
        if ((shm_buf = (struct env_info *)shmat (shmid, NULL, 0)) == (void *)-1)
        {
            perror ("shmat");
            exit (-1);
        }
    }

    bzero (shm_buf, sizeof (struct env_info));
}

void refresh_mem (link_datatype *buf)
{
    *shm_buf = *buf;
    printf ("x=%d, y=%d,z=%d,ill=%d\n", shm_buf->x, shm_buf->y, shm_buf->z, shm_buf->ill);
}

void *pthread_analysis (void *arg)
{
    linklist node;
    link_datatype buf;
    struct env_info * ret;

    printf ("pthread_analysis is ok\n");
    ret = (struct env_info *)malloc(sizeof(struct env_info));
    init_mem();
    while (1)
    {
        pthread_mutex_lock (&mutex_analysis);
        pthread_cond_wait (&cond_analysis, &mutex_analysis);
        pthread_mutex_unlock (&mutex_analysis);

        while (1)
        {
            pthread_mutex_lock (&mutex_linklist);
            if ((node = linklist_get (ret)) == NULL)
            {
                pthread_mutex_unlock (&mutex_linklist);
                break;
            }
            buf = node->data;
            free (node);
            pthread_mutex_unlock (&mutex_linklist);
            refresh_mem (&buf);
        }
    }
    return 0;
}